package com.czy;

import com.alibaba.fastjson2.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class 读取dify流式数据 {


    public static void main(String[] args) throws Exception {
        File file = new File("F:\\OneDrive\\Desktop\\新建文本文档.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        String s;
        while ((s = br.readLine()) != null) {
            if(!s.startsWith("data:")) continue;
            s = s.substring(5);
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONObject.parseObject(s);
            } catch (Exception e) {
                System.out.println(s);
                throw new RuntimeException(e);
            }
            if("message_end".equals(jsonObject.getString("event"))) break;
            String string = jsonObject.getString("answer");
            System.out.print(decodeUnicode(string));
        }
        System.out.println();
    }

    private static String decodeUnicode(String input) {
        StringBuilder sb = new StringBuilder();
        int length = input.length();
        for (int i = 0; i < length; i++) {
            char c = input.charAt(i);
            if (c == '\\' && i + 1 < length && input.charAt(i+1) == 'u') {
                String hex = input.substring(i+2, Math.min(i+6, length));
                try {
                    int codePoint = Integer.parseInt(hex, 16);
                    sb.append((char) codePoint);
                    i += 5; // 跳过已处理的部分
                } catch (NumberFormatException e) {
                    sb.append(c);
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }


}